package vip.xiaonuo.common.tenant;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

/**
 * @author zjt
 * @description
 * @date 2025/2/8 09:39
 */
@Slf4j
public class TenantContext {
    private static final ThreadLocal<Boolean> FILTER_ENABLED = ThreadLocal.withInitial(() -> true);

    // 禁用租户过滤
    public static void disableTenantFilter() {
        FILTER_ENABLED.set(false);
    }

    // 启用租户过滤
    public static void enableTenantFilter() {
        FILTER_ENABLED.set(true);
    }

    public static Boolean isFilterEnabled() {
        return FILTER_ENABLED.get();
    }

    /**
     * 移除ThreadLocal
     */
    public static void clear() {
        FILTER_ENABLED.remove();
    }

    public static void ignoreHandle(Runnable handle) {
        try {
            disableTenantFilter();
            handle.run();
        } catch (Exception e) {
            log.error("忽略租户执行任务出现异常", e);
        } finally {
            enableTenantFilter();
            clear();
        }
    }


    public static <T> T ignoreHandle(Callable<T> handle) {
        try {
            disableTenantFilter();
            return handle.call();
        } catch (Exception e) {
            log.error("忽略租户执行任务出现异常", e);
            throw new RuntimeException(e);
        } finally {
            enableTenantFilter();
            clear();
        }
    }

}
